#include "ThresholdOTSU.h"
#include <math.h>



int ThresholdOTSU::calcThresholdValue (const vector< int > & histogram)
{
  int c = 0;
  for (int i = 0; i < histogram.size (); ++i)
	  c += histogram[i];
  double cxc = (double)c * c;
  double c0 = 0;
  double c1 = c;
  double s0 = 0;
  double s1 = 0;
  for (int i = 0; i < 256; ++i)
    s1 += (double)histogram[i] * i;

  double gMax = 0;
  int tMax = 0;

  for (int t = 1; t <= 256; ++t) {
    c0 += (double)histogram[t - 1];
    c1 -= (double)histogram[t - 1];
    s0 += (double)histogram[t - 1] * (t - 1);
    s1 -= (double)histogram[t - 1] * (t - 1);
    double g;
    if (c0 == 0.0 || c1 == 0.0)
      g = 0;
    else
      g = pow (s1 * c0 - s0 * c1, (double)2.0f) / cxc / c0 / c1;
    if (g > gMax) {
      gMax = g;
      tMax = t;
    }
  }

  return tMax;
}
